
import axios from "axios";


const userservers = axios.create({
    baseURL:'/other',
    timeout:60000
})

userservers.interceptors.request.use(function (config: any) {
    config.headers['token'] = localStorage.getItem('token') || ''
    return config;
}, function (error: any) {
    return Promise.reject(error);
});



userservers.interceptors.response.use(function (response) {
    return response;
}, function (error: any) {
    return Promise.reject(error);
});


interface iConfig {
    url: string,
    method: string,
    data?: any
    headers?: any
}


export default function userajax(config: iConfig) {
    const { url = '', method = 'post', data = {}, headers = {} } = config
    switch (method.toUpperCase()) {
        case 'GET':
            return userservers.get(url, { params: data })
        case 'POST':
            if (headers['Content-Type'] == 'application/x-www-form-urlencoded') {
                const obj = new URLSearchParams()
                for (const key in data) {
                    obj.append(key, data[key])
                }
                return userservers.post(url, obj, { headers })
            }

            if (headers['Content-Type'] == 'multipart/form-data') {
                const obj = new FormData()
                for (const key in data) {
                    obj.append(key, data[key])
                }
                return userservers.post(url, obj, { headers })
            }
            return userservers.post(url, data)
        case 'DELETE':
            return userservers.delete(url, { data })
        case 'PUT':
            return userservers.put(url, data)
        case "PATCH":
            return userservers.patch(url, data)
        default:
            return userservers.request(config)
    }
}